"""LeadTag repository implementation (Synchronous)."""

from __future__ import annotations

from sqlalchemy.orm import Session, joinedload
from sqlalchemy import func

from ..models.lead_tag import LeadTag
from ..repositories.base import Repository
from ..schemas.lead_tag import LeadTagCreate, LeadTagUpdate


class LeadTagRepository(Repository[LeadTag, LeadTagCreate, LeadTagUpdate]):
    """Repository for LeadTag operations (Synchronous)."""

    def __init__(self, session: Session) -> None:
        super().__init__(LeadTag, session)

    def get_by_lead(self, lead_id: int) -> list[LeadTag]:
        """获取Lead的所有标签（包含Tag详情）."""
        return (
            self.session.query(LeadTag)
            .options(joinedload(LeadTag.tag))
            .filter(LeadTag.lead_id == lead_id)
            .order_by(LeadTag.confidence.desc())
            .all()
        )

    def get_by_tag(self, tag_id: int, skip: int = 0, limit: int = 100) -> list[LeadTag]:
        """获取使用某标签的所有Lead."""
        return (
            self.session.query(LeadTag)
            .options(joinedload(LeadTag.lead))
            .filter(LeadTag.tag_id == tag_id)
            .order_by(LeadTag.created_at.desc())
            .offset(skip)
            .limit(limit)
            .all()
        )

    def get_by_lead_and_tag(self, lead_id: int, tag_id: int) -> LeadTag | None:
        """检查Lead是否已有某标签."""
        return (
            self.session.query(LeadTag)
            .filter(LeadTag.lead_id == lead_id, LeadTag.tag_id == tag_id)
            .first()
        )

    def delete_by_lead(self, lead_id: int) -> int:
        """删除Lead的所有标签，返回删除数量."""
        count = self.session.query(LeadTag).filter(LeadTag.lead_id == lead_id).delete()
        self.session.flush()
        return count

    def delete_by_lead_and_tag(self, lead_id: int, tag_id: int) -> bool:
        """删除Lead的指定标签."""
        lead_tag = self.get_by_lead_and_tag(lead_id, tag_id)
        if lead_tag:
            self.session.delete(lead_tag)
            self.session.flush()
            return True
        return False

    def count_by_tag(self, tag_id: int) -> int:
        """统计使用某标签的Lead数量."""
        return (
            self.session.query(func.count(LeadTag.id)).filter(LeadTag.tag_id == tag_id).scalar()
            or 0
        )

    def get_by_source(self, source: str, skip: int = 0, limit: int = 100) -> list[LeadTag]:
        """根据来源获取标签（ai/rule/manual）."""
        return (
            self.session.query(LeadTag)
            .options(joinedload(LeadTag.tag), joinedload(LeadTag.lead))
            .filter(LeadTag.source == source)
            .order_by(LeadTag.created_at.desc())
            .offset(skip)
            .limit(limit)
            .all()
        )
